package org.example.thymeleaf.demo.demos.controller;



import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.TextRenderData;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.example.thymeleaf.demo.demos.entity.MergeTemplate;
import org.example.thymeleaf.demo.demos.service.MergeTemplateService;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;

/**
 * (MergeTemplate)表控制层
 *
 * @author makejava
 * @since 2024-09-11 10:44:10
 */
@RestController
@RequestMapping("/mergeTemplate")
public class MergeTemplateController{
    /**
     * 服务对象
     */
    @Resource
    private MergeTemplateService mergeTemplateService;


    @GetMapping("/show/{id}")
    public String showById(@PathVariable("id") Integer id ){
        byte[] templateValue = mergeTemplateService.getById(id).getTemplateValue();
        return Base64.getEncoder().encodeToString(templateValue);
    }

    @RequestMapping ("/download/{id}")
    public void downloadWord(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
        MergeTemplate mergeTemplate = mergeTemplateService.getById(id);
        byte[] templateValue = mergeTemplate.getTemplateValue();

        // 2. 将字节数组写入到临时文件中
        File tempFile = File.createTempFile("template_", ".docx");
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(templateValue); // 将字节数组写入临时文件
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 3. 使用 poi-tl 来加载这个临时文件并替换 {{orgName}} 占位符
        try (XWPFTemplate template = XWPFTemplate.compile(tempFile)) {
            // 定义替换的变量及其值
            template.render(new HashMap<String, Object>() {{
                put("orgName", new TextRenderData(mergeTemplate.getCompanyName())); // 替换 {{orgName}} 的内容
            }});

            // 4. 将修改后的 docx 文件输出为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            template.write(outputStream);

            // 5. 设置响应头，返回修改后的 docx 文件供下载
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=modified_template.docx");
            response.getOutputStream().write(outputStream.toByteArray());
            response.flushBuffer();
        } finally {
            // 删除临时文件
            tempFile.delete();
        }
    }

}

